package cn.simon.service;

import cn.simon.mapper.CartMapper;
import cn.simon.model.Cart;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Kinfer
 * @date 2022/10/31
 */
@Service
public class CartService {
    @Autowired
    private CartMapper cartMapper;

    /**
     * 加入购物车
     *
     * @param cart
     * @return
     * @author Kinfer
     * @date 2022/10/31
     */
    public int addCart(Cart cart) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", cart.getGoodsId());
        Cart cart1 = cartMapper.selectOne(queryWrapper);
        // 如果购物车中商品已存在，修改其数量
        if (cart1 != null) {
            UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("cart_goods_number", cart1.getCartGoodsNumber() + cart.getCartGoodsNumber());
            updateWrapper.eq("cart_id", cart1.getCartId());
            cartMapper.update(cart, updateWrapper);
            return 1;
        }
        cartMapper.insert(cart);
        return 1;
    }

    /**
     * 通过userId查询用户购物车内所有商品
     *
     * @param userId
     * @return
     * @author Kinfer
     * @date 2022/10/31
     */
    public List<Cart> getCart(Integer userId) {
        return cartMapper.getCartByUserId(userId);
    }

    /**
     * 删除购物测内指定商品
     *
     * @param cartId
     * @return
     * @author Kinfer
     * @date 2022/10/31
     */
    public int delCart(Integer cartId) {
        cartMapper.deleteById(cartId);
        return 1;
    }

    /**
     * 删除购物测内所有商品
     *
     * @param userId
     * @return
     * @author Kinfer
     * @date 2022/10/31
     */
    public int delAllCart(Integer userId) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        cartMapper.delete(wrapper);
        return 1;
    }
}
